package com.lingjtx.ai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.thread.api.WebClientApi;
import com.lingjtx.common.thread.commom.ApiKeyFilter;
import com.lingjtx.common.thread.commom.NettyServerExceptionResolver;
import com.lingjtx.common.thread.commom.RestResponseConfig;
import com.lingjtx.common.thread.config.ObjectPoolTemplateConfig;
import com.lingjtx.common.thread.pooling.ObjectPoolTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class AiConfig {

    @Value("${dify.url}")
    private String difyUrl;

    @Value("${dify.apikey}")
    private String apikey;

    @Bean("difyClient")
    public WebClient getClient() {
        return WebClient.builder()
                .baseUrl(difyUrl) // Dify 接口地址
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(Const.AuthTokenMap.AUTHORIZATION, "Bearer " + apikey)
                .build();
    }

    @Bean
    public ApiKeyFilter apiKeyFilter() {
        return new ApiKeyFilter();
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(RestResponseConfig config) {
        return config.jacksonObjectMapper();
    }

    @Bean
    public NettyServerExceptionResolver resolver() {
        return new NettyServerExceptionResolver();
    }

    @Bean("webClientObjectPoolTemplate")
    public ObjectPoolTemplate<WebClient> webClientObjectPoolTemplate(ObjectPoolTemplateConfig config) {
        return config.webClientObjectPoolTemplate();
    }

    @Bean
    public WebClientApi webClientApi(ObjectPoolTemplateConfig config) {
        return config.webClientApi();
    }
}
